package battleroom;

import com.jme3.bullet.PhysicsSpace;
import com.jme3.bullet.PhysicsTickListener;
import com.jme3.bullet.collision.PhysicsCollisionEvent;
import com.jme3.bullet.collision.PhysicsCollisionListener;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.collision.shapes.SphereCollisionShape;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.math.Vector3f;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author Adam
 */
public class PlayerBody extends RigidBodyControl
                    implements PhysicsTickListener, PhysicsCollisionListener{
    private final PlayerState playerState;
    List<StarControl> collisions = new ArrayList();
    private StarControl collidedWith;
    private int timer;
    
    
    public PlayerBody(CollisionShape shape, PlayerState pstate){
        super(shape);       
        
        setMass(64f);
        enableCollisions();
        
        this.playerState = pstate;
        
        setLinearVelocity(Vector3f.ZERO);
    }
    
    public void enableCollisions()
    {        
        setCollideWithGroups(COLLISION_GROUP_03);
        setCollisionGroup(COLLISION_GROUP_01);
    }
    
    public void disableCollisions()
    {        
        setCollideWithGroups(COLLISION_GROUP_NONE);
        setCollisionGroup(COLLISION_GROUP_NONE);
    }
    
    @Override
    public void update(float tpf)
    {
        if(collidedWith != null)
        {
            timer++;
            
            if(timer*tpf > .7)
            {
                collidedWith = null;
                timer = 0;
            }
        }
        
    }
    
    @Override
    public void prePhysicsTick(PhysicsSpace space, float f) {
        if(playerState.isAttached())
        {
            setLinearVelocity(Vector3f.ZERO);
        }
    }

    @Override
    public void physicsTick(PhysicsSpace space, float f) {
        if(!getLinearVelocity().equals(Vector3f.ZERO))
        {     
            float speed = PlayerState.clampSpeed(getLinearVelocity().length());
            float mod = speed/getLinearVelocity().length();
            setLinearVelocity(getLinearVelocity().mult(mod));    
        }
    }
    
    @Override
    public void collision(PhysicsCollisionEvent event) {
        if(event.getObjectA().getCollisionGroup() != this.getCollisionGroup()) return;
        
        StarControl sc = event.getNodeB().getControl(StarControl.class);
        if(sc != null)
        {
            collidedWith = sc;
        }
    }
    
    public boolean hasCollidedWith(StarControl star)
    {
        if(collidedWith == null) return false;
        return collidedWith.equals(star);
    }
}
